import sys
import asyncio
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QProgressBar, QVBoxLayout, QWidget

# 工作线程类（集成协程支持）
class AsyncWorker(QThread):
    progress = pyqtSignal(int)
    finished = pyqtSignal(str)

    def run(self):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        
        try:
            task = loop.create_task(self.async_task())  # 使用loop.create_task
            loop.run_until_complete(task)
        except Exception as e:
            self.finished.emit(f"错误: {str(e)}")
        finally:
            loop.close()

    async def async_task(self):
        for i in range(101):
            await asyncio.sleep(0.05)
            self.progress.emit(i)
        return "任务完成"

# 主窗口类
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("PyQt协程多线程示例")
        self.setGeometry(100, 100, 300, 150)
        
        # UI组件
        self.progress = QProgressBar(self)
        self.progress.setRange(0, 100)
        
        self.button = QPushButton("开始任务")
        self.button.clicked.connect(self.start_task)
        
        # 布局
        layout = QVBoxLayout()
        layout.addWidget(self.progress)
        layout.addWidget(self.button)
        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)
        
        # 线程实例
        self.worker = AsyncWorker()
        self.worker.progress.connect(self.update_progress)
        self.worker.finished.connect(self.task_finished)

    def start_task(self):
        """启动工作线程"""
        self.progress.setValue(0)
        self.button.setEnabled(False)
        self.worker.start()

    def update_progress(self, value):
        """更新进度条"""
        self.progress.setValue(value)

    def task_finished(self, result):
        """任务完成处理"""
        print(result)
        self.button.setEnabled(True)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())